<template>
  <div class="statisticsListPage h100">
    <!-- 服务异常统计标题及搜索 -->
    <div class="statisticsListSearch">
      <!-- <h2 class="title18">{{ $t('fwyctj') }}</h2> -->
      <div class="statisticsListSearchCont">
        <a-row :gutter="[8, 16]" style="display: flex;flex-wrap: wrap;align-items: center;">
          <!-- 车型 -->
          <a-col
            :xs="12"
            :sm="12"
            :md="12"
            :lg="12"
            :xl="6"
            :xxl="6"
          >
            <car-model-select
              :query="{ time: 0 }"
              :defaultValue="queryParams.modelIds"
              :maxTagCount="1"
              placeholder="车型"
              @changeoption="selectCarModel"
              :hasAll="false"
              :clear="true"
              style="width:100%;height:32px;overflow: hidden;"
              mode="multiple">
            </car-model-select>
          </a-col>
          <!-- VIN -->
          <a-col
            :xs="12"
            :sm="12"
            :md="12"
            :lg="12"
            :xl="4"
            :xxl="5"
            style="margin-bottom:6px;"
          >
            <a-input
              :placeholder="$t('pleaseInput') + 'VIN'"
              size="small"
              v-model="queryParams.vin"
              @keyup.enter="searchData"
              :allow-clear="true"/>
          </a-col>
          <!-- 操作开始时间与结束时间 -->
          <a-col
            :xs="12"
            :sm="12"
            :md="12"
            :lg="12"
            :xl="7"
            :xxl="6"
          >
            <a-range-picker
              :placeholder="[$t('actionStartTime'), $t('actionEndTime')]"
              show-time
              @change="onTimeRangeChange"
              :value="defaultTimeRange"
              :disabled-date="disabledDate"
              :allow-clear="true"
              style="width:100%;"
            />
          </a-col>
          <!--<a-col-->
            <!--:xs="12"-->
            <!--:sm="12"-->
            <!--:md="12"-->
            <!--:lg="12"-->
            <!--:xl="7"-->
            <!--:xxl="7"-->
          <!--&gt;-->
            <div class="searchBtns">
              <a-button-group>
                <auth-button type="primary" :auth="statisticsPerms.serviceClientLog.view" @click="searchData">
                  <i class="iconfont icon-chazhao"/>{{ $t('inquiry') }}
                </auth-button>
                <a-button @click="clearCondition">
                  <i class="iconfont icon-qingkong"/>{{ $t('clear') }}
                </a-button>
              </a-button-group>
              <!-- 导出明细 -->
              <auth-button
                type="primary"
                :loading="exportingDetail"
                :auth="statisticsPerms.serviceClientLog.export"
                @click="exportDetail">
                <i class="iconfont icon-xiazai"/>{{ $t('exportDetail') }}
              </auth-button>
              <!-- 导出分布 -->
              <auth-button
                type="primary"
                :loading="exportingDistribute"
                :auth="statisticsPerms.serviceClientLog.distributeExport"
                @click="exportDistribute"
                class="lastExportBtn">
                <i class="iconfont icon-xiazai"/>{{ $t('exportDistribute') }}
              </auth-button>
            </div>
          <!--</a-col>-->
        </a-row>
      </div>
    </div>
    <div class="statisticsListMain">
      <!-- 服务异常统计表格列表 -->
      <div class="statisticsListMainLeft">
        <s-table
          ref="table"
          size="default"
          rowKey="id"
          :columns="columns"
          :data="loadData"
          class="h100">
          <template slot-scope="text" v-for="column in commonColumns" :slot="column.scopedSlots.customRender">
            <table-ellipsis :text="text || '-'" :key="column.key"></table-ellipsis>
          </template>
          <template #reportingTime="text">
            <table-ellipsis :text="$commonFun.getDateTimeStr(text)"></table-ellipsis>
          </template>
          <template #expiration="text">
            <table-ellipsis :text="$commonFun.getDateStr(text)"></table-ellipsis>
          </template>
          <template #operateType="text">
            <table-ellipsis :text="$t(text === 0 ? 'powerOnSelfTest' : 'userActivation')"></table-ellipsis>
          </template>
          <template slot="operation" slot-scope="text, record">
            <auth-button
              v-if="record.id"
              :auth="statisticsPerms.serviceClientLog.download"
              type="primary"
              :ghost="true"
              size="small"
              @click="downloadFile(record)"><i class="iconfont icon-xiazai"/>{{ $t('downLog') }}</auth-button>
            <span v-else>-</span>
          </template>
        </s-table>
      </div>
      <!-- 服务异常车型分布 -->
      <div class="statisticsListMainRight">
        <full-parent-dom-with-dask :loading="loadingModelStatisticsData"></full-parent-dom-with-dask>
        <h4 class="">{{ $t('distribution') }}</h4>
        <ul class="modelExceptionCountLists">
          <li class="modelExceptionCountListItem" v-for="model in modelStatisticsData" :key="model.id">
            <span class="modelExceptionCountListItemText">
              <table-ellipsis :text="model.modelInfo"></table-ellipsis>
            </span>
            <span class="modelExceptionCountListItemNum">
              <table-ellipsis :text="model.count"></table-ellipsis>
            </span>
          </li>
          <li v-if="modelStatisticsData.length === 0" class="modelExceptionCountListItem">{{ $t('noData') }}</li>
        </ul>
        <div class="exceptionIndexPagination">
          <a-pagination
            v-show="totalCount"
            simple
            :current="pageInfo.pageNo"
            :total="totalCount"
            :pageSize="pageInfo.pageSize"
            @change="changePageSize" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import CarModelSelect from '@/views/components/CarModelSelect'
import { serviceExceptionColumns } from './config/list'
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import { STable } from '@/components'
import FullParentDomWithDask from '@/components/LoadDataSpin/FullParentDomWithDask.vue'
import logApi from '@/api/modules/log'
import subscriptionQueryApi from '@/api/modules/system/subscriptionQuery'
import { downloadBlobFile } from '@/utils/functions'
import AuthButton from '@/components/AuthButton'
import AuthText from '@/components/AuthText'
import { statisticsPerms } from '@/config/permission/index'
import moment from 'moment'
const initQueryParams = {
  vin: '',
  taskName: '',
  // 车型
  modelIds: [],
  startTime: '',
  endTime: ''
}
export default {
  components: {
    CarModelSelect,
    STable,
    TableEllipsis,
    FullParentDomWithDask,
    AuthButton,
    AuthText
  },
  data () {
    return {
      statisticsPerms,
      exporting: false,
      columns: serviceExceptionColumns,
      queryParams: {
        ...initQueryParams
      },
      // 服务异常车型分布数据
      modelStatisticsData: [],
      loadingModelStatisticsData: true,
      pageInfo: {
        pageSize: 14,
        pageNo: 1
      },
      totalCount: 0,
      exportingDetail: false,
      exportingDistribute: false
    }
  },
  computed: {
    commonColumns () {
      return this.columns.filter(item => !item.special)
    },
    // 有效期选择的默认值
    defaultTimeRange () {
      if (this.queryParams.startTime && this.queryParams.endTime) {
        return [moment(this.queryParams.startTime), moment(this.queryParams.endTime)]
      }
      return []
    }
  },
  created () {
    this.getModelstatisticsData()
  },
  methods: {
    searchData () {
      this.refreshData()
      this.getModelstatisticsData()
    },
    clearCondition () {
      this.queryParams = { ...initQueryParams }
      this.searchData()
    },
    selectCarModel (val) {
      this.queryParams.modelIds = val
      this.searchData()
    },
    // 导出明细
    exportDetail () {
      this.exportingDetail = true
      logApi.exportServiceExceptionLogDetail(this.queryParams).then(res => {
        downloadBlobFile(res, this.$t('logDetail') + '.xlsx')
      }).finally(() => {
        this.exportingDetail = false
      })
    },
    // 导出分布
    exportDistribute () {
      this.exportingDistribute = true
      logApi.exportServiceExceptionLogDistribute(this.queryParams).then(res => {
        downloadBlobFile(res, this.$t('updateExceptionModelDistribute') + '.xlsx')
      }).finally(() => {
        this.exportingDistribute = false
      })
    },
    loadData (parameter) {
      return logApi.getServiceExceptionLog({ ...this.queryParams, ...parameter })
    },
    refreshData (isToFirstPage = true) {
      let obj = null
      if (isToFirstPage) {
        obj = { current: 1 }
      }
      this.$refs.table.loadData(obj)
    },
    // 获取服务异常车型分布
    getModelstatisticsData () {
      const params = {
        ...this.queryParams
      }
      this.modelstatisticsData = []
      this.loadingModelStatisticsData = true
      logApi.getServiceExceptionDistribute(params).then(res => {
        if (!res.data) {
          return
        }
        this.modelStatisticsData = res.data.map(item => {
          let modelInfo = item.modelCode
          if (item.modelName) {
            modelInfo += '[' + item.modelName + ']'
          }
          if (item.trimLevel) {
            modelInfo += '[' + item.trimLevel + ']'
          }
          return {
            id: item.modelId,
            modelInfo,
            count: item.exceptCnt
          }
        })
      }).finally(() => {
        this.loadingModelStatisticsData = false
      })
    },
    changePageSize (page) {
      this.pageInfo.pageNo = page
      this.loadData()
    },
    // 下载日志
    downloadFile (record) {
      this.downing = true
      subscriptionQueryApi.downloadServiceVehicleLog({ id: record.id }).then(res => {
        downloadBlobFile(res, record.id + '_' + record.vin + '_' + record.orderNum + '.txt')
      }).finally(() => {
        this.downing = false
      })
    },
    // eslint-disable-next-line consistent-return
    onTimeRangeChange (date, dateString) {
      if (date.length === 0) {
        this.queryParams.startTime = ''
        this.queryParams.endTime = ''
        return false
      }
      // eslint-disable-next-line prefer-destructuring
      this.queryParams.startTime = dateString[0]
      // eslint-disable-next-line prefer-destructuring
      this.queryParams.endTime = dateString[1]
    },
    disabledDate (current) {
      return current > moment()
    }
  }
}
</script>
<style lang="less" scoped>
.statisticsListPage {
  display: flex;
  flex-direction: column;

  .statisticsListSearch {
    flex: none;
    display: flex;
    padding: 20px 24px 10px 24px;
    border-bottom: 1px solid @borderColor;

    .title18 {
      flex: none;
      margin-right: 120px;
    }

    .statisticsListSearchCont {
      flex: 1 0 0;
    }
  }

  .statisticsListMain {
    flex: 1 0 0;
    overflow: hidden;
    display: flex;

    .statisticsListMainLeft {
      flex: 1 0 0;
      padding: 20px 24px;
      overflow: hidden;
    }

    .statisticsListMainRight {
      position: relative;
      flex: 290px 0 0;
      border-left: 1px solid @borderColor;
      padding: 20px 10px;
      display: flex;
      flex-direction: column;

      >h4 {
        font-weight: bold;
        font-size: 1.1em;
        margin-bottom: 5px;
        flex: none;
      }
    }

    // 服务异常车型分布
    .modelExceptionCountLists {
      flex: 1 0 0;
      min-height: 200px;

      .modelExceptionCountListItem {
        display: flex;
        justify-content: space-between;
        line-height: 40px;
      }

      .modelExceptionCountListItemText {
        flex: 190px 0 0;
      }

      .modelExceptionCountListItemNum {
        width: 50px;
        flex: none;
        text-align: right;
      }
    }

    .exceptionIndexPagination {
      flex: none;
      margin-top: 10px;
    }
  }
}
</style>
<style lang="less">
.statisticsListSearchCont {
  .disabledAuthButtonWrap:nth-last-child(1) {
    margin-right: 0;
  }
  .ant-select-selection--multiple {
    max-height: 33px;
    overflow-y: auto;
    overflow-x: hidden;
  }
}
</style>
